import gzip
import hmac
import base64
import hashlib
import json
import datetime
from requests import Request


def format_symbol(symbol):
    return symbol.replace('/', '')


def resume_symbol(contract):
    if contract.endswith('usdt'):
        symbol = contract[:-4] + '/usdt'
        return symbol
    err = 'Huobi trading for {} not implemented'.format(contract)
    raise NotImplementedError(err)


def pong(ws, ping):
    ping = json.loads(ping)
    pong = {'pong': ping['ping']}
    message = json.dumps(pong)
    ws.send(message)


def unzip(message):
    return gzip.decompress(message).decode('utf-8')


def build_req(host, path, method, params, api_key, secret_key):
    url_params = {
        'SignatureMethod': 'HmacSHA256',
        'SignatureVersion': '2',
        'Timestamp': datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S'),
        'AccessKeyId': api_key,
    }

    if method == 'GET':
        url_params.update(params)
        body = None
    else:
        body = json.dumps(params)
    signature = sign(host, path, method, url_params, secret_key)
    url_params['Signature'] = signature

    # url = f'{rest_host}{path}?{self._url_encode(url_params)}'
    url = host + path
    header = method_header[method]

    req = Request(method, url, header, data=body, params=url_params)
    return req


def sign(host, path, method, params, secret_key):
    sorted_params = sorted(params.items(), key=lambda d: d[0], reverse=False)
    encode_params = parse(sorted_params)
    target = host.split('://')[1]
    payload = '{}\n{}\n{}\n{}'.format(method, target, path, encode_params)

    digest = hmac.new(secret_key.encode(), payload.encode(), digestmod=hashlib.sha256).digest()
    signature = base64.b64encode(digest)
    signature = signature.decode()
    return signature


def parse(sorted_params):
    result = '&'.join(['{}={}'.format(i, j) for i, j in sorted_params])
    while ':' in result:
        result = result.replace(':', '%3A')
    return result


method_header = {
    'GET': {"Content-Type": "application/x-www-form-urlencoded"},
    'POST': {'Content-Type': 'application/json'}
}
